package com.whmall.service.crm.module.company.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whmall.common.enumeration.YesNoEnum;
import com.whmall.component.entity.dto.OperatorReqDTO;
import com.whmall.component.entity.dto.PageReqDTO;
import com.whmall.component.entity.dto.PageRspDTO;
import com.whmall.component.enumeration.CompanyDailyRegisterInformationSubTypeEnum;
import com.whmall.component.enumeration.CompanyDailyRegisterInformationTypeEnum;
import com.whmall.service.crm.entity.dto.company.*;
import com.whmall.service.crm.module.company.dao.CompanyMapper;
import com.whmall.service.crm.module.company.entity.CompanyDO;
import com.whmall.service.crm.module.company.entity.CompanyDailyRegisterInformationDO;
import com.whmall.service.crm.module.company.entity.CompanyEventDO;
import com.whmall.service.crm.module.company.service.CompanyDailyRegisterInformationService;
import com.whmall.service.crm.module.company.dao.CompanyDailyRegisterInformationMapper;
import lombok.extern.slf4j.Slf4j;
import com.whmall.component.service.AbstractDbService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service
public class CompanyDailyRegisterInformationServiceImpl extends AbstractDbService<CompanyDailyRegisterInformationMapper, CompanyDailyRegisterInformationDO>
            implements CompanyDailyRegisterInformationService{

    @Autowired
    private CompanyMapper companyMapper;

    @Override
    public PageRspDTO<CompanyDailyRegisterInfoRspDTO> page(PageReqDTO pageReqDTO, CompanyDailyRegisterInfoQueryReqDTO queryReqDTO) {
        LambdaQueryWrapper<CompanyDailyRegisterInformationDO> queryWrapper = makeCondition(queryReqDTO);

        IPage<CompanyDailyRegisterInformationDO> page = super.page(Page.of(pageReqDTO.getPageNum(),pageReqDTO.getPageSize()),queryWrapper);
        if(CollUtil.isEmpty(page.getRecords())){
            return PageRspDTO.EMPTY;
        }

        return PageRspDTO.of(pageReqDTO,(int) page.getPages(),(int) page.getTotal(),page.getRecords().stream().map(r -> {
            CompanyDailyRegisterInfoRspDTO rspDTO = new CompanyDailyRegisterInfoRspDTO();
            BeanUtils.copyProperties(r,rspDTO);
            return rspDTO;
        }).collect(Collectors.toList()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(CompanyDailyRegisterInfoCreateDTO reqDTO, OperatorReqDTO operatorReqDTO) {
        CompanyDailyRegisterInformationDO informationDO = new CompanyDailyRegisterInformationDO();
        BeanUtils.copyProperties(reqDTO,informationDO);
        informationDO.setCreateId(operatorReqDTO.getOperatorId());
        informationDO.setCreateTime(new Date());
        super.save(informationDO);
        // 更新公司上的合作状态
        setCompanyCooperationState(reqDTO.getCompanyId(), reqDTO.getType1(), reqDTO.getType2(),operatorReqDTO);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(CompanyDailyRegisterInfoUpdateDTO reqDTO, OperatorReqDTO operatorReqDTO) {
        CompanyDailyRegisterInformationDO exist = super.getById(reqDTO.getId());
        Assert.isTrue(null != reqDTO.getId() && null != exist,"请求参数异常");
        CompanyDailyRegisterInformationDO informationDO = new CompanyDailyRegisterInformationDO();
        BeanUtils.copyProperties(reqDTO,informationDO);
        informationDO.setUpdateId(operatorReqDTO.getOperatorId());
        informationDO.setUpdateTime(new Date());
        super.updateById(informationDO);
        // 更新公司上的合作状态
        setCompanyCooperationState(exist.getCompanyId(), reqDTO.getType1(), reqDTO.getType2(),operatorReqDTO);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeById(Long id, OperatorReqDTO operatorReqDTO) {
        Assert.isTrue(null != id && null != super.getById(id),"请求参数异常");
        CompanyDailyRegisterInformationDO companyDailyRegisterInformationDO = new CompanyDailyRegisterInformationDO();
        companyDailyRegisterInformationDO.setId(id);
        companyDailyRegisterInformationDO.setIsDeleted(YesNoEnum.YES.getCode());
        companyDailyRegisterInformationDO.setUpdateId(operatorReqDTO.getOperatorId());
        companyDailyRegisterInformationDO.setUpdateTime(new Date());
        super.updateById(companyDailyRegisterInformationDO);
    }

    /**
     * 根据日常维护类型更新公司合作状态
     * @param companyId 公司id
     * @param type1 维护类型
     * @param type2 维护类型子类型
     */
    private void setCompanyCooperationState(Long companyId, Integer type1,Integer type2,OperatorReqDTO operatorReqDTO){

        // 合作关系
        if(CompanyDailyRegisterInformationTypeEnum.COOPERATIVE_RELATIONSHIP.getValue() == type1){

            CompanyDO companyDO = companyMapper.selectById(companyId);
            Assert.isTrue(null != companyDO,"请求参数异常");

            Integer isCooperated = type2 == CompanyDailyRegisterInformationSubTypeEnum.NORMAL_COOPERATION.getValue()?1:0;

            // 合作状态匹配不更新
            if(companyDO.getIsCooperated().equals(isCooperated)){
                return;
            }

            CompanyDO updateDo = new CompanyDO();
            updateDo.setId(companyId);
            updateDo.setIsCooperated(isCooperated);
            updateDo.setUpdateId(operatorReqDTO.getOperatorId());
            updateDo.setUpdateTime(new Date());
            companyMapper.updateById(updateDo);
            return;

        }
    }

    /**
     * 组装分页查询条件
     * @param queryReqDTO
     * @return
     */
    private LambdaQueryWrapper<CompanyDailyRegisterInformationDO> makeCondition(CompanyDailyRegisterInfoQueryReqDTO queryReqDTO){
        LambdaQueryWrapper<CompanyDailyRegisterInformationDO> queryWrapper = Wrappers.lambdaQuery();
        Map<SFunction<CompanyDailyRegisterInformationDO,?>,Object> map = new HashMap<>();
        map.put(CompanyDailyRegisterInformationDO::getCompanyId,queryReqDTO.getCompanyId());
        map.put(CompanyDailyRegisterInformationDO::getIsDeleted,queryReqDTO.getIsDeleted());
        map.put(CompanyDailyRegisterInformationDO::getType1,queryReqDTO.getType1());
        map.put(CompanyDailyRegisterInformationDO::getType2,queryReqDTO.getType2());
        queryWrapper.allEq(map,false);
        queryWrapper.ge(ObjectUtil.isNotNull(queryReqDTO.getTimeGte()),CompanyDailyRegisterInformationDO::getCreateTime,queryReqDTO.getTimeGte());
        queryWrapper.le(ObjectUtil.isNotNull(queryReqDTO.getTimeLte()),CompanyDailyRegisterInformationDO::getCreateTime,queryReqDTO.getTimeLte());
        queryWrapper.orderByDesc(CompanyDailyRegisterInformationDO::getCreateTime);
        return queryWrapper;
    }
}